package risk.control.application.activity.myself;


import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import risk.control.application.MainApplication;
import risk.control.application.R;
import risk.control.application.activity.base.BaseActivity;
import risk.control.application.entity.TransactionRecordBean;
import risk.control.application.http.Api;
import risk.control.application.http.callback.UiCallback;
import risk.control.application.utils.CameraPermissionHelper;
import risk.control.application.utils.RouteJump;
import risk.control.application.utils.data.TokenUtils;

/**
 * 是否本人
 */
public class MyselfActivity extends BaseActivity implements LifecycleOwner {

    private TextView mTvTitle;
    private Button mBtnTakePic;

    private TextView mTvReminder;

    private Button mBtnSubmit;

    private LinearLayout mLlAgent;

    private EditText mEtUserName;
    private EditText mEtIdNumber;
    private EditText mEtPhoneNumber;

    //摄像头权限
    private ActivityResultLauncher<String> cameraPermissionLauncher;
    private CameraPermissionHelper.PermissionCallback permissionCallback;

    private BroadcastReceiver mReceiver;

    @Override
    protected void postData(HashMap<String, String> dataMap) {
        if (mEtUserName != null) {
            mEtUserName.setText(dataMap.get("userName"));
        }
        if (mEtIdNumber != null) {
            mEtIdNumber.setText(dataMap.get("idNumber"));
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myself);
        intiView();
        intiData();
        initListener();
    }


    private void intiView() {
        mTvTitle = findViewById(R.id.tv_result_title);
        mBtnTakePic = findViewById(R.id.btn_take_pic);
        mTvReminder = findViewById(R.id.tv_reminder);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mLlAgent = findViewById(R.id.ll_agent);
        mEtUserName = findViewById(R.id.edit_name);
        mEtIdNumber = findViewById(R.id.edit_id_number);
        mEtPhoneNumber = findViewById(R.id.edit_phone);
    }

    @SuppressLint("SetTextI18n")
    private void intiData() {
        //接收数据
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            finish();
            return;
        }
        String title = bundle.getString("title");
        //根据标题展示不同页面
        if (title != null && title.equals("本人")) {
            mTvTitle.setText("本人取款");
            mLlAgent.setVisibility(GONE);
        } else {
            mTvTitle.setText("非本人取款");
            mLlAgent.setVisibility(VISIBLE);
        }

        mTvReminder.setText("人证核验提醒，请核对：\n" +//
                "1、人脸与证件照是否一致\n" +//
                "2、证件防伪标识是否清晰\n" +//
                "3、姓名、号码等信息是否匹配");//
        registerReceiver();
    }


    private void initListener() {
        //权限回调
        permissionCallback = new CameraPermissionHelper.PermissionCallback() {
            @Override
            public void onPermissionGranted() {
                //跳转页面
                startIDCarScanActivity();
            }
        };
        // 创建权限请求Launcher
        cameraPermissionLauncher = CameraPermissionHelper.createPermissionLauncher(this, permissionCallback);
        mBtnTakePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 检查并请求摄像头权限
                CameraPermissionHelper.requestCameraPermission(MyselfActivity.this, cameraPermissionLauncher, permissionCallback);
            }
        });

        mBtnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();

            }
        });

    }

    private void submit() {
        String agentName = mEtUserName.getText().toString();
        String agentIdNumber = mEtIdNumber.getText().toString();
        String agentPhoneNumber = mEtPhoneNumber.getText().toString();
        //写入全局数据
        TransactionRecordBean transactionRecordBean = MainApplication.transactionRecordBean;
        transactionRecordBean.agentName = agentName;
        transactionRecordBean.agentIdNumber = agentIdNumber;
        transactionRecordBean.agentPhoneNumber = agentPhoneNumber;

        //发起请求
        showLoadDialog("正在提交...");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", TokenUtils.get());
        params.put("withdrawalType", transactionRecordBean.withdrawalType);
        params.put("withdrawalsName", transactionRecordBean.withdrawalsName);
        params.put("idNumber", transactionRecordBean.idNumber);
        params.put("phoneNumber", transactionRecordBean.phoneNumber);
        params.put("withdrawalTime", transactionRecordBean.withdrawalTime);
        params.put("withdrawalAmount", transactionRecordBean.withdrawalAmount);
        params.put("currency", transactionRecordBean.currency);
        params.put("transactionChannel", transactionRecordBean.transactionChannel);
        params.put("withdrawalReason", transactionRecordBean.withdrawalReason);
        params.put("cardIssuancePlace", transactionRecordBean.cardIssuancePlace);
        params.put("isSelfWithdrawal", transactionRecordBean.isSelfWithdrawal);
        params.put("agentName", transactionRecordBean.agentName);
        params.put("agentIdNumber", transactionRecordBean.agentIdNumber);
        params.put("agentPhoneNumber", transactionRecordBean.agentPhoneNumber);
        getNetWordData(Api.riskInquiry, params, new UiCallback() {
            @Override
            public void onSuccess(String respData) {
                dismissLoadDialog();
                //提交成功，发送关闭页面的广播
                Intent intent = new Intent("destroy-activity-action"); // 自定义 Action
                intent.putExtra("key", "value"); // 可携带附加数据
                sendBroadcast(intent);
                //跳转查询结果页
                JSONObject jsonObject = (JSONObject) JSON.parse(respData);
                JSONObject data = jsonObject.getJSONObject("data");
                String riskLevel = data.getString("riskLevel");
                String desc = data.getString("desc");
                Map<String, Object> params = new HashMap<>();
                params.put("riskLevel", riskLevel);
                params.put("desc", desc);
                //清空表单
                MainApplication.transactionRecordBean = new TransactionRecordBean();
                RouteJump.start(MyselfActivity.this, RouteJump.QUERY_RESULT_ACTION, params, true, true);
            }

            @Override
            public void onSpecialCode(String errorData) {
                dismissLoadDialog();
            }

            @Override
            public void onResolve() {
                dismissLoadDialog();
            }
        });
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("destroy_activity_action");//关闭当前页面
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                finish();
            }
        };
        //只允许接受本app
        ContextCompat.registerReceiver(this, mReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }


    //获取当前时间
    @SuppressLint("SimpleDateFormat")
    public static String getCurrentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm").format(System.currentTimeMillis());
    }

}





